from rest_framework import serializers
from myapp.models import Visitor
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser


class VisitorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Visitor
        fields = ['ctype', 'cid', 'name', 'phone']


@csrf_exempt
def visitor_list(request):
    if request.method == 'GET':
        v = Visitor.objects.all()
        serializer = VisitorSerializer(v, many=True)
        return JsonResponse(serializer.data, status=200, safe=False)


def visitor_add(request):
    data = request.GET
    serializer = VisitorSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=200)
    return JsonResponse(serializer.errors, status=400)


@csrf_exempt
def visitor(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        v = Visitor.objects.get(pk=pk)
    except Visitor.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = VisitorSerializer(v)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = VisitorSerializer(v, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        v.delete()
        return HttpResponse(status=204)
